package com.xjoyt.pay.master.core.order.handle.callback;

import java.util.Date;

import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import com.xjoyt.pay.dto.ExecuteResult;
import com.xjoyt.pay.gateway.params.CallbackParam;
import com.xjoyt.pay.master.core.order.handle.AbstractOrderCallbackHandle;
import com.xjoyt.pay.master.dto.CallbackResult;
import com.xjoyt.pay.master.po.Order;
import com.xjoyt.pay.master.repository.OrderConfigRepository;
import com.xjoyt.pay.master.repository.OrderRepository;

/**
 * 处理回调
 * 
 * @author Administrator
 *
 */
@Component
public class CallbackHandle extends AbstractOrderCallbackHandle {

	@Autowired
	private RestTemplate restTemplate;

	@Autowired
	private OrderRepository repository;

	@Autowired
	private OrderConfigRepository orderConfigRepository;

	@Override
	public ExecuteResult<CallbackResult> handle(CallbackParam param, Order order) throws Exception {
		if (BooleanUtils.isNotTrue(order.done)) {
			CallbackResult callback = restTemplate.postForObject(order.orderConfig.callbackUrl, param,
					CallbackResult.class);
			if (callback.success) {
				order.doneDate = new Date();
				order.done = true;
				if (StringUtils.isBlank(order.tradeNo) && StringUtils.isNotBlank(callback.tradeNo)) {
					order.tradeNo = callback.tradeNo;
				}
				order = repository.save(order);
				order.orderConfig.callbackResult = callback.callbackResult;
				order.orderConfig.callbackResponse = callback.callbackResponse;
				order.orderConfig = orderConfigRepository.save(order.orderConfig);
			} else {
				if (StringUtils.isNotBlank(callback.callbackResponse)) {
					order.orderConfig.callbackResponse = callback.callbackResponse;
					order.orderConfig = orderConfigRepository.save(order.orderConfig);
				}
			}
		}
		return getNext().handle(param, order);
	}

}
